<?php 
	Class MultiUploadBehavior extends ModelBehavior
	{
		var $default = array("type"=>"hasMany","uploadModelName"=>"Assets.Asset");
		
		/**
		 * (non-PHPdoc)
		 * @see libs/model/ModelBehavior#setup($model, $config)
		 */
		var $settings = array();
		function setup($model,$config)
		{
			$this->settings[$model->alias] = am($this->default,$config);
			$this->settings[$model->alias]['uploadModel'] = cri($this->settings[$model->alias]['uploadModelName']);
			$this->createBinding($model);
			$this->appendAdditionalFields($model);
		}
		
		function createBinding($model)
		{			
			extract($this->settings[$model->alias]);

			$model->bindModel(array($type => array(
					$uploadModel->alias => array("className" => $uploadModelName,"dependent" => true )
			)),false);
			if(!isset($uploadModel->belongsTo[$model->alias]))
			{
				$uploadModel->bindModel(array('belongsTo'=>array(
					$model->alias => array("className"=>$model->className)
				)),false);
			}
			
		}
		
		function appendAdditionalFields($model)
		{
			if($this->settings[$model->alias]['type']=="hasOne" || $this->settings[$model->alias]["uploadModel"]->hasField("is_default"))
			{		
				if(!isset($model->additionalFields))
				{
					$model->additionalFields =array();
				}
				if(!in_array('uploadedFile',$model->additionalFields))
				{
					array_push($model->additionalFields,"uploadedFile");
					$model->cacheFields["uploadedFile"] = "+5 minutes";
				}
				
			}
			
		}
		
		function uploadedFile($model,$result)
		{
			extract($this->settings[$model->alias]);
			if(!isset($model->{$type}[$uploadModel->alias]) || !isset($result[$model->alias][$model->primaryKey]) || ($type=="hasMany"	&& $this->settings[$model->alias]["uploadModel"]->hasField("is_default")==false))
			{			
				return ;
			}
			$foreignKey = $model->{$type}[$uploadModel->alias]["foreignKey"];
			$condition[] = array($foreignKey => $result[$model->alias][$model->primaryKey]);
			$orderBy = null;
			if($type=="hasMany"	&& $this->settings[$model->alias]["uploadModel"]->hasField("is_default"))
			{
				//check for default first else we will use normal asset.
				//$condition[] = array("is_default" => 1);
				$orderBy = "$uploadModel->alias.is_default DESC";
				if($uploadModel->hasField("created"))
				{
					$orderBy .= ",$uploadModel->alias.created DESC";
				}
			} 
			if(isset($this->settings[$model->alias]["uploadModel"]->scopes['published']))
			{
				$condition[] = $this->settings[$model->alias]["uploadModel"]->scopes['published'];
			}		
					
			$value = $uploadModel->field("name",$condition,$orderBy);
			$value = $value === false ? null : $value;
			
			return $value;
		}
	}

?>